import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_shop/model/categorygood.dart';
import 'package:flutter_shop/routers/application.dart';
import 'package:flutter_shop/service/service_method.dart';
import 'package:provide/provide.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../provide/category_goods_list.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../provide/childcategory.dart';
import 'package:fluttertoast/fluttertoast.dart';
//商品列表，可以上拉加载
class CategoryGoodsList extends StatefulWidget {
  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }
  //刷新插件要求的
  GlobalKey<RefreshFooterState> _footerKey =
      new GlobalKey<RefreshFooterState>();
  var scorllController=new ScrollController();
  @override
  Widget build(BuildContext context) {
    return Provide<CategoryGoodsListProvide>(
      builder: (context, child, data) {
        //加载变化大类
        try{
          if(Provide.value<ChildCategory>(context).page==1){
            //列表位置，放到最上面
            scorllController.jumpTo(0.0);
          }
        }catch(e){
          print('进入页面第一次初始化：${e}');
        }
        if(data.goodsList.length>0){
        return Expanded(
          child: Container(
            width: ScreenUtil().setWidth(570),
            child:EasyRefresh(
              refreshFooter: ClassicsFooter(
                    key: _footerKey,
                    bgColor: Colors.white,
                    textColor: Colors.pink,
                    moreInfoColor: Colors.pink,
                    showMore: true,
                    noMoreText: Provide.value<ChildCategory>(context).noMoreText,
                    loadingText: '加载中',
                    loadText: '加载完成',
                    moreInfo: '加载更多',
                    loadReadyText: '上拉加载....'),
                    child: ListView.builder(
                        controller: scorllController,
                        itemCount: data.goodsList.length,
                        itemBuilder: (context, index) {
                          return _listWidget(data.goodsList, index);
                        },
                    ),
                    loadMore: ()async{
                      _getMoreList();
                      print("上拉加载更多");
                    },
            )   
          ),
        );}
        else{
            return  Text('暂时没有数据');
        }
      },
    );
  }
   void _getMoreList() async {
     Provide.value<ChildCategory>(context).addPage();
    var data = {
      'categoryId': Provide.value<ChildCategory>(context).categoryId,
      'categorySubId': Provide.value<ChildCategory>(context).subId,
      'page':Provide.value<ChildCategory>(context).page,
    };
    await request('getMallGoods', formData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodListModel goodlist = CategoryGoodListModel.fromJson(data);
      if(goodlist.data==null){
        Fluttertoast.showToast(
          msg: "已经到底了",
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          backgroundColor: Colors.pink,
          textColor: Colors.white,
          fontSize: 16.0
        );
        Provide.value<ChildCategory>(context).changeNoMore("没有更多了");}
      else
      Provide.value<CategoryGoodsListProvide>(context)
          .getMoreList(goodlist.data);
    });
  }

  Widget _goodsImage(List newList, int index) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(newList[index].image),
    );
  }

  Widget _goodsName(List newList, int index) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        newList[index].goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  Widget _goodsPrice(List newList, int index) {
    return Container(
        margin: EdgeInsets.only(top: 20.0),
        width: ScreenUtil().setWidth(370),
        child: Row(children: <Widget>[
          Text(
            '价格:￥${newList[index].presentPrice}',
            style:
                TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            '￥${newList[index].oriPrice}',
            style: TextStyle(
                color: Colors.black26, decoration: TextDecoration.lineThrough),
          )
        ]));
  }

  Widget _listWidget(List newList, int index) {
    return InkWell(
        onTap: () {
             Application.router.navigateTo(context, "/detail?id=${newList[index].goodsId}");
        },
        child: Container(
          padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
          decoration: BoxDecoration(
              color: Colors.white,
              border: Border(
                  bottom: BorderSide(width: 1.0, color: Colors.black12))),
          child: Row(
            children: <Widget>[
              _goodsImage(newList, index),
              Column(
                children: <Widget>[
                  _goodsName(newList, index),
                  _goodsPrice(newList, index)
                ],
              )
            ],
          ),
        ));
  }
}
